package cn.airfei.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @description:
 * @author: air
 * @create: 2021-01-14 14:43
 */
public class NIOClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        // 设置为非阻塞
        socketChannel.configureBlocking(false);
        // 链接服务器
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8888);
        System.out.println("链接了一个服务器:"+inetSocketAddress.getAddress());
        System.out.println(inetSocketAddress.getHostString());

        if (!socketChannel.connect(inetSocketAddress)){
            while (!socketChannel.finishConnect()){
                System.out.println("因为链接需要时间,客户端不会阻塞,可以做其他工作...");
            }
            String str="hello air";

            ByteBuffer wrap = ByteBuffer.wrap(str.getBytes());
            // 发送数据,将buffer中的数据写入channel
            socketChannel.write(wrap);
            System.in.read();

        }
    }

}
